//
//  LKAggregatePaymentViewController.m
//  Mideleague_Agent
//
//  Created by Zhiwang on 2020/5/22.
//  Copyright © 2020 Zhiwang. All rights reserved.
//

#import "LKAggregatePaymentViewController.h"
#import <Masonry/Masonry.h>
#import "LKBaseView.h"
#import "LKDefineFile.h"
#import "LKAggregatePaymentHomeCell.h"
#import "LKMyShopViewController.h"
#import "LKManagerAllianceViewController.h"
#import <SDCycleScrollView.h>
#import "LKAggregatePaymentHomeHeaderCell.h"
#import "LKMySubordinateViewController.h"
#import "LKOpenShopStepOneViewController.h"
#import "LKHomeDataModel.h"
#import "LKManagerSuboradinateViewController.h"
#import "LKMyTradeCountViewController.h"
#import "LKAboutUsViewController.h"
#import "LKBackCommissionViewController.h"
@interface LKAggregatePaymentViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,SDCycleScrollViewDelegate>

@property(nonatomic,strong)UICollectionView *collectionView;
@property(nonatomic,strong)UICollectionViewFlowLayout *flowLayout;
@property(nonatomic,strong)LKBaseLabel *moneyLabel;
@property(nonatomic,strong)LKBaseLabel *numbersLabel;
@property(nonatomic,strong)NSArray *titlesArray;
@property(nonatomic,strong)NSArray *iconsArray;
@property(nonatomic,strong)UIPageControl *pageControl;
@property(nonatomic,strong)SDCycleScrollView *cycleScrollView;
@property(nonatomic,strong)NSMutableArray *dataArray;
@property(nonatomic,strong)NSMutableArray *headerModelArray;
@property(nonatomic,strong)LKHomeDataModel *dataModel;
@property(nonatomic,strong)NSArray *bottomShowArray;
@property(nonatomic,strong)YYTimer *timer;
@end

@implementation LKAggregatePaymentViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = viewDefualtColor;
    [self createCollectionUI];
    [self getHomeInformationDataWithType];
    //    0: 所有1 :今日 2:昨日 3:本周 4:本月 5:上周 6:上月 7 为自定义时间
    self.dataArray = [[NSMutableArray alloc] initWithArray:@[@"今日数据" ,@"昨日数据",@"本周数据",@"本月数据"]];
    self.bottomShowArray = @[@"商户今日收入(元)",@"商户昨日收入(元)",@"商户本周收入(元)",@"商户本月收入(元)"];
    self.iconsArray = @[@"ic_main_my_merchant",@"ic_main_merchant_open",@"ic_main_delivery_ranking",@"ic_main_merchant_manage",@"ic_main_agent_open",@"ic_main_member_manage"];
    self.titlesArray = @[@"我的商户",@"商户开通",@"交易统计",@"下级代理",@"代理开通",@"聚合费率返佣"];
//    [self createSDCycleScrollViewWithView:self.view];
//    [self createCollectionUI];
    // Do any additional setup after loading the view.
}
-(void)createSDCycleScrollViewWithView:(UIView *)view{
    self.cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, WIDTH, 253) imageNamesGroup:@[@"编组 2",@"编组 2",@"编组 2",@"编组 2"]];
    _cycleScrollView.delegate = self;
    self.cycleScrollView.infiniteLoop = NO;
    _cycleScrollView.currentPageDotColor = [UIColor whiteColor];
    _cycleScrollView.pageDotColor = yellowDefaultColor;
    _cycleScrollView.bannerImageViewContentMode = UIViewContentModeScaleAspectFill;
    _cycleScrollView.autoScroll = NO;
    [view addSubview:_cycleScrollView];
    if (@available(iOS 11.0, *)) {
        [UIScrollView appearance].contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;//UIScrollView也适用
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
}
-(UINib *)customCollectionViewCellNibForCycleScrollView:(SDCycleScrollView *)view{
    if (view != _cycleScrollView) {
        return nil;
    }
    return [UINib nibWithNibName:@"LKAggregatePaymentHomeHeaderCell" bundle:nil];
}
-(void)setupCustomCell:(UICollectionViewCell *)cell forIndex:(NSInteger)index cycleScrollView:(SDCycleScrollView *)view{
    LKAggregatePaymentHomeHeaderCell *customView = (LKAggregatePaymentHomeHeaderCell *)cell;
    customView.dateSting = self.dataArray[index];
    customView.bottomSting = self.bottomShowArray[index];
    if (self.headerModelArray.count != 0) {
        if (index == 0) {
            
        }
        if (self.headerModelArray.count > 3) {
            customView.homeModel = self.headerModelArray[index];
        }
    }else{
        
    }
//    customView.homeModel = self.headerModelArray[index];
    customView.bgImageView.image = [UIImage imageNamed:@"编组 2"];
    NSLog(@"%@",self.dataArray[index]);
}
//- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didScrollToIndex:(NSInteger)index{
//
//}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = NO;
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}
/**
 创建collectioview的布局
 */
-(void)createCollectionUI{
    self.collectionView.scrollsToTop = YES;
    self.flowLayout = [[UICollectionViewFlowLayout alloc] init];
    self.flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:self.flowLayout];
    [self.view addSubview:self.collectionView];
    self.collectionView.backgroundColor = viewDefualtColor;
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
        if (@available(iOS 11.0, *)) {
        self.collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        // Fallback on earlier versions
    }
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.view.mas_top).offset(0);
        make.bottom.equalTo(self.view.mas_bottom).offset(-TAB_BAR_HEIGHT);
    }];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
    
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"LKAggregatePaymentHomeCell" bundle:nil] forCellWithReuseIdentifier:@"LKAggregatePaymentHomeCell"];
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerReloadData)];

}
/// 下拉刷新
-(void)headerReloadData{
//    [self.cycleScrollView removeFromSuperview];
//    [self.collectionView removeFromSuperview];
//    [self createCollectionUI];
    [self getHomeInformationDataWithType];
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.titlesArray.count;

}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
        LKAggregatePaymentHomeCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"LKAggregatePaymentHomeCell" forIndexPath:indexPath];
        cell.titlleLabel.text = self.titlesArray[indexPath.row];
        cell.iconImageView.image = [UIImage imageNamed:self.iconsArray[indexPath.row]];
        return cell;
}
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if ([kind isEqual:UICollectionElementKindSectionHeader]) {
        UICollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"header" forIndexPath:indexPath];
        for (UIView *subView in header.subviews) {
            [subView removeFromSuperview];
        }
        [self createSDCycleScrollViewWithView:header];
        LKBaseLabel *workBenchLabel = [LKBaseLabel labelWithFrame:CGRectZero text:@"工作台" textColor:labelBlackColor font:[UIFont fontWithName:@"PingFangSC-Medium" size:16] textAlignment:NSTextAlignmentCenter];
        [header addSubview:workBenchLabel];
        [workBenchLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.cycleScrollView.mas_bottom).offset(5);
            make.centerX.equalTo(header);
        }];
        return header;
    }else{
        UICollectionReusableView *footer = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"footer" forIndexPath:indexPath];
        return footer;
    }
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeMake(WIDTH, 42 + 253);
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    return CGSizeZero;
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake((WIDTH - 3)/3, 115);
}
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 1;
}
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 1;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.row) {
        case 0:
        {
            LKMyShopViewController *myShopVc = [[LKMyShopViewController alloc] init];
            myShopVc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:myShopVc animated:YES];
        }
            break;
        case 1:
        {
            LKManagerAllianceViewController *mgAlianceVc = [[LKManagerAllianceViewController alloc] init];
            mgAlianceVc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:mgAlianceVc animated:YES];
        }
            break;
        case 2:
        {
            LKMyTradeCountViewController *mgAlianceVc = [[LKMyTradeCountViewController alloc] init];
            mgAlianceVc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:mgAlianceVc animated:YES];
        }
            break;
        case 3:
        {
            LKMySubordinateViewController *mgAlianceVc = [[LKMySubordinateViewController alloc] init];
            mgAlianceVc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:mgAlianceVc animated:YES];
        }
            break;
        case 4:
        {
           LKManagerSuboradinateViewController *mgSubordVc = [[LKManagerSuboradinateViewController alloc] init];
           mgSubordVc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:mgSubordVc animated:YES];
            

        }
            break;
        case 5:
        {
           LKBackCommissionViewController *backVc = [[LKBackCommissionViewController alloc] init];
           backVc.hidesBottomBarWhenPushed = YES;
           [self.navigationController pushViewController:backVc animated:YES];
            

        }
            break;
        default:
            break;
    }

}

/// 添加首页数据
-(void)getHomeInformationDataWithType{
    [self.headerModelArray removeAllObjects];
//    0: 所有1 :今日 2:昨日 3:本周 4:本月 5:上周 6:上月 7 为自定义时间
//    dispatch_queue_t queue = dispatch_queue_create("peiDuo", DISPATCH_QUEUE_CONCURRENT);
    dispatch_group_t group = dispatch_group_create();
    dispatch_queue_t serial = dispatch_queue_create(0, DISPATCH_QUEUE_CONCURRENT);
    dispatch_group_enter(group);
    dispatch_group_async(group, serial, ^{
        //请求1
        [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:MyHomePageInforamtionUrl header:[LKUserInforTool account].token parameters:@{@"type":@"1"} progress:^(NSProgress * _Nullable progress) {
            
        } success:^(BOOL isSuccess, id  _Nullable responseObject) {
            dispatch_group_leave(group);
            if ([responseObject[@"code"] isEqualToString:@"success"]) {
                LKHomeDataModel *dataModel = [LKHomeDataModel modelWithDictionary:responseObject[@"data"]];
                    dataModel.TypeId = @"1";
                [self.headerModelArray addObject:dataModel];
                NSLog(@"1");
            }else{
            }
        } failure:^(NSString * _Nullable errorMessage) {
            
        }];
    });
    dispatch_group_enter(group);
    dispatch_group_async(group, serial, ^{
        [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:MyHomePageInforamtionUrl header:[LKUserInforTool account].token parameters:@{@"type":@"2"} progress:^(NSProgress * _Nullable progress) {
            
        } success:^(BOOL isSuccess, id  _Nullable responseObject) {
            dispatch_group_leave(group);
            if ([responseObject[@"code"] isEqualToString:@"success"]) {
                LKHomeDataModel *dataModel = [LKHomeDataModel modelWithDictionary:responseObject[@"data"]];
                    dataModel.TypeId = @"2";
                [self.headerModelArray addObject:dataModel];
                                NSLog(@"2");
            }else{
            }
        } failure:^(NSString * _Nullable errorMessage) {
            
        }];
    });
    dispatch_group_enter(group);
        dispatch_group_async(group, serial, ^{
            [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:MyHomePageInforamtionUrl header:[LKUserInforTool account].token parameters:@{@"type":@"3"} progress:^(NSProgress * _Nullable progress) {
                
            } success:^(BOOL isSuccess, id  _Nullable responseObject) {
                dispatch_group_leave(group);
                if ([responseObject[@"code"] isEqualToString:@"success"]) {
                    LKHomeDataModel *dataModel = [LKHomeDataModel modelWithDictionary:responseObject[@"data"]];
                    dataModel.TypeId = @"3";
                    [self.headerModelArray addObject:dataModel];
                }else{
                }
            } failure:^(NSString * _Nullable errorMessage) {
                
            }];
        });
    dispatch_group_enter(group);
    dispatch_group_async(group, serial, ^{
        [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:MyHomePageInforamtionUrl header:[LKUserInforTool account].token parameters:@{@"type":@"4"} progress:^(NSProgress * _Nullable progress) {
            
        } success:^(BOOL isSuccess, id  _Nullable responseObject) {
            dispatch_group_leave(group);
            if ([responseObject[@"code"] isEqualToString:@"success"]) {
                LKHomeDataModel *dataModel = [LKHomeDataModel modelWithDictionary:responseObject[@"data"]];
                dataModel.TypeId = @"4";
                [self.headerModelArray addObject:dataModel];
            }else{
                
            }
        } failure:^(NSString * _Nullable errorMessage) {
            
        }];
    });


    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
         [self.headerModelArray sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
             LKHomeDataModel *model1 = obj1;
             LKHomeDataModel *model2 = obj2;
             if ([model1.TypeId integerValue] < [model2.TypeId integerValue]) {
                 return NSOrderedAscending;
             }else{
                 return NSOrderedDescending;
                 
             }
        }];
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView reloadData];
    });
}
-(NSMutableArray *)headerModelArray{
    if (_headerModelArray == nil) {
        _headerModelArray = [[NSMutableArray alloc] init];
    }
    return _headerModelArray;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
